package com.learn.http.util;

import com.learn.logback.log.LogTest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
public class NetWorkConnection {

    private final static Logger log = LoggerFactory.getLogger(NetWorkConnection.class);

    //当前文件开始位置
    public static long offset=0;
    private static ProgressListener progressListener=new ProgressListener() {
        @Override
        public void onUpdate(long bytesRead, long contentLength, boolean done) {
            log.debug("onUpdate: " + bytesRead + ">>" + contentLength + ">>" + done);
        }
    };
    //本地文件路径
    private String filePath;
    //线程停止标识
    public volatile static boolean isStopSendFileFlag=false;

    public static void main(String[] args) {

        sendRecv(0,"C:\\Users\\acer\\Desktop\\1.pdf");
    }
    public static void sendRecvx(long offset, String fileName){
        File file = new File(fileName);
        try(FileInputStream fis = new FileInputStream(file)){
            String remoteURL="http://localhost:8080";
            log.info("远程服务地址：{}",remoteURL);
            URL url = new URL(remoteURL+"/file/recv");
            fis.skip(offset);

            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            //HttpURLConnection conn = HttpsConnectionUtil.getHttpURLConnection(remoteURL+"/file/recv");
            //设置超时间为10秒
            conn.setConnectTimeout(100*1000);
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", "application/octet-stream");
            conn.setRequestProperty("filename", URLEncoder.encode(file.getName(), "utf-8"));
            conn.setRequestProperty("offset", "" + offset);
            conn.setRequestProperty("fileLength", "" + file.length());
            conn.setFixedLengthStreamingMode(file.length()-offset);
            OutputStream os = conn.getOutputStream();
            byte[] buf = new byte[1024 * 100];


            int read = 0;
            while (!isStopSendFileFlag && (read = fis.read(buf)) != -1){
                os.write(buf, 0, read);

            }
            os.flush();

            if(isStopSendFileFlag) {
                conn.disconnect();
                return;
            }

            String result = "";
            InputStream inputStream = conn.getInputStream();
            while ((read = inputStream.read(buf)) != -1){
                result += new String(buf, 0, read, "UTF-8");
            }
            conn.disconnect();
            log.info("recv result:"+result);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            log.info("请求异常{}",e.getMessage());
            e.printStackTrace();
        }
    }
    public static void sendRecv(long offset, String fileName){
        File file = new File(fileName);
        try(FileInputStream fis = new FileInputStream(file)){
            String remoteURL="http://localhost:8080";
            log.info("远程服务地址：{}",remoteURL);
            URL url = new URL(remoteURL+"/file/recv");
            fis.skip(offset);

            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            //HttpURLConnection conn = HttpsConnectionUtil.getHttpURLConnection(remoteURL+"/file/recv");
            //设置超时间为10秒
            conn.setConnectTimeout(100*1000);
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", "application/octet-stream");
            conn.setRequestProperty("filename", URLEncoder.encode(file.getName(), "utf-8"));
            conn.setRequestProperty("offset", "" + offset);
            conn.setRequestProperty("fileLength", "" + file.length());
            conn.setFixedLengthStreamingMode(file.length()-offset);
            OutputStream os = conn.getOutputStream();

            byte[] buf = new byte[1024 * 100];

            //初始化进度
            if (progressListener != null)
                progressListener.onUpdate(0, conn.getContentLength(), false);

            int read = 0;
            while (!isStopSendFileFlag && (read = fis.read(buf)) != -1){
                os.write(buf, 0, read);
                //下载过程中的进度
                if (progressListener != null)
                    progressListener.onUpdate(1,conn.getContentLength(), false);
            }
            os.flush();

            //下载完成
            if (progressListener != null)
                progressListener.onUpdate(1, 1, true);

            if(isStopSendFileFlag) {
                conn.disconnect();
                return;
            }

            String result = "";
            InputStream inputStream = conn.getInputStream();
            while ((read = inputStream.read(buf)) != -1){
                result += new String(buf, 0, read, "UTF-8");
            }
            conn.disconnect();
            log.info("recv result:"+result);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            log.info("请求异常{}",e.getMessage());
            e.printStackTrace();
        }
    }

}
